package estore.network;

import estore.service.ProductService5;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 电子商城服务器
 */
public class EStoreServer5 {
    private final ProductService5 productService;
    private final int port;

    public EStoreServer5(int port) {
        this.port = port;
        this.productService = new ProductService5();
    }

    public void start() {
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("🖥️  电子商城服务器已启动，监听端口: " + port);
            System.out.println("等待客户端连接...");

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("✅ 客户端连接: " + clientSocket.getInetAddress().getHostAddress());

                // 为每个客户端创建新线程处理
                new Thread(() -> handleClient(clientSocket)).start();
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败: " + e.getMessage());
        }
    }

    private void handleClient(Socket clientSocket) {
        try (ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
             ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream())) {

            while (true) {
                try {
                    // 读取客户端请求
                    String request = (String) ois.readObject();
                    System.out.println("收到请求: " + request);

                    Object response = processRequest(request);
                    oos.writeObject(response);
                    oos.flush();

                } catch (EOFException e) {
                    // 客户端断开连接
                    break;
                } catch (ClassNotFoundException e) {
                    System.err.println("请求格式错误: " + e.getMessage());
                    oos.writeObject("ERROR: 无效的请求格式");
                }
            }
        } catch (IOException e) {
            System.out.println("客户端断开连接: " + e.getMessage());
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                System.err.println("关闭客户端连接失败: " + e.getMessage());
            }
        }
    }

    private Object processRequest(String request) {
        try {
            switch (request) {
                case "GET_ALL_PRODUCTS":
                    return productService.getAllProducts();

                case "GET_AVAILABLE_PRODUCTS":
                    return productService.getAvailableProducts();

                case "SEARCH_PRODUCTS_BY_NAME":
                    return "PLEASE_SEND_KEYWORD";

                case "GET_PRODUCT_BY_ID":
                    return "PLEASE_SEND_PRODUCT_ID";

                case "DECREASE_STOCK":
                    return "PLEASE_SEND_STOCK_INFO";

                case "CHECK_STOCK":
                    return "PLEASE_SEND_CHECK_INFO";

                case "EXIT":
                    return "BYE";

                default:
                    // 处理带参数的请求
                    if (request.startsWith("SEARCH:")) {
                        String keyword = request.substring(7);
                        return productService.searchProductsByName(keyword);
                    } else if (request.startsWith("GET_PRODUCT:")) {
                        String productId = request.substring(12);
                        return productService.findProductById(productId);
                    } else if (request.startsWith("DECREASE:")) {
                        String[] parts = request.substring(9).split(":");
                        if (parts.length == 2) {
                            boolean success = productService.decreaseStock(parts[0], Integer.parseInt(parts[1]));
                            return success ? "SUCCESS" : "FAILED";
                        }
                    } else if (request.startsWith("CHECK:")) {
                        String[] parts = request.substring(6).split(":");
                        if (parts.length == 2) {
                            boolean available = productService.checkStock(parts[0], Integer.parseInt(parts[1]));
                            return available ? "AVAILABLE" : "UNAVAILABLE";
                        }
                    }
                    return "ERROR: 未知的请求: " + request;
            }
        } catch (Exception e) {
            return "ERROR: " + e.getMessage();
        }
    }

    public static void main(String[] args) {
        EStoreServer5 server = new EStoreServer5(8888);
        server.start();
    }
}